import sys
sys.path.append("../../")

from controller.dfcf.TuShareCalc import *
import re, urllib.request
import requests
from model.StockBaseInfo import *
import pandas as pd
import numpy as np
import akshare as ak
import httpx
import httpcore

class StockAnalysys:
    headers = {
        'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,'
                  'application/signed-exchange;v=b3;q=0.9',
        'Accept-Encoding': 'gzip, deflate, br',
        'Accept-Language': 'zh-CN,zh;q=0.9',
        'Cache-Control': 'max-age=0',
        'Connection': 'close',
        'Cookie': 'timezoneOffset=28800,0; _ga=GA1.2.2068924460.1568258364; browserid=1637567403399993326; '
                  'sessionid=0be65a169d686e464855602e; _gid=GA1.2.614169347.1590475272; '
                  'steamMachineAuth76561199007171441=CA87107A153BDC24FE6D54504A124395F9C36243; '
                  'deep_dive_carousel_focused_app=673750; deep_dive_carousel_method=gems; '
                  'steamCountry=HK%7C413cfd508f5a328ba1679f9252231a8e; '
                  'app_impressions=377530@1_7_7_topsellers_150_3|1245200@1_7_7_topsellers_150_3|632360'
                  '@1_7_7_topsellers_150_3|1245180@1_7_7_topsellers_150_3|1298590@1_7_7_topsellers_150_3|285900'
                  '@1_7_7_topsellers_150_3|632470@1_7_7_topsellers_150_2|813780@1_7_7_topsellers_150_2|1100600'
                  '@1_7_7_topsellers_150_2|1293820@1_7_7_topsellers_150_2|952860@1_7_7_topsellers_150_2|1209110'
                  '@1_7_7_topsellers_150_2|1015610@1_7_7_topsellers_150_3|1238440@1_7_7_topsellers_150_3|1042550'
                  '@1_7_7_topsellers_150_3|466560@1_7_7_topsellers_150_3|602960@1_7_7_topsellers_150_3|457140'
                  '@1_7_7_topsellers_150_3|793460@1_7_7_topsellers_150_3|512540@1_7_7_topsellers_150_3|619150'
                  '@1_7_7_topsellers_150_3|1100410@1_7_7_topsellers_150_3|1088780@1_7_7_topsellers_150_3|1100420'
                  '@1_7_7_topsellers_150_3|1201360@1_7_7_topsellers_150_3|642280@1_7_7_topsellers_150_3|673950'
                  '@1_7_7_topsellers_150_3|613830@1_7_7_topsellers_150_3|636480@1_7_7_topsellers_150_3|387990'
                  '@1_7_7_topsellers_150_3|414700@1_7_7_topsellers_150_3|382310@1_7_7_topsellers_150_3|1162520'
                  '@1_7_7_topsellers_150_2|289070@1_7_7_topsellers_150_2|307690@1_7_7_topsellers_150_2|973760'
                  '@1_7_7_topsellers_150_2|1273370@1_5_9__405; recentapps=%7B%22578080%22%3A1590476900%7D',
        'Sec-Fetch-Mode': 'navigate',
        'Sec-Fetch-Site': 'same-origin',
        'Sec-Fetch-User': '?1',
        'Upgrade-Insecure-Requests': '1',
        'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64; rv:52.0) Gecko/20210911 Firefox/52.0'
    }

    def __init__(self):
        pass

    def transferCode(self,code,type=1):
        subfix = code[:1]
        if subfix == "6":
            if type == 1:
                return code + ".SH"
            else:
                return "SH" + code
        else:
            if type == 1:
                return code + ".SZ"
            else:
                return "SZ" + code

    def getCompanyInfo(self,code):
        componyurl = "http://data.eastmoney.com/dataapi/stockdata/f10api?type=PCF10/RptCompanyProfile&post" \
                     "Data={%22SecurityCode%22:%20%22" + self.transferCode(code) + "%22}&fields=CorpName,Representative,RegistryAddress," \
                                                                 "RegistryCapital,BusinessRange,CorpSummary"
        response = requests.get(componyurl)
        return response.json()

    def getManageInfo(self,code):
        stock_main_stock_holder_df = ak.stock_main_stock_holder(stock=code)
        rs = []
        cnt = 0
        for index,row in stock_main_stock_holder_df.iterrows():
            rs.append({"gudong":row["股东名称"],"hand":str(row["持股比例(%)"])+"%"})
            cnt += 1
            if cnt > 9:
                break
        return rs

    def getAllInfo(self,code):
        url = "http://data.eastmoney.com/stockcomment/api/" + code + ".json"
        response = requests.get(url)
        return response.json()

    def run(self,code='000001.SZ'):
        code = code[0:6]
        print(code)
        subfix = code[:1]
        if subfix == "6":
            code1 = code + ".SH"
            code2 = "SH" + code
        else:
            code1 = code + ".SZ"
            code2 = "SZ" + code
        content = "<hr>"
        content += "【公司情况】" + "<br/>"
        componyurl = "http://data.eastmoney.com/dataapi/stockdata/f10api?type=PCF10/RptCompanyProfile&post" \
                     "Data={%22SecurityCode%22:%20%22" + code1 + "%22}&fields=CorpName,Representative,RegistryAddress," \
                     "RegistryCapital,BusinessRange,CorpSummary"
        response = requests.get(componyurl)
        companydata = response.json()
        content += companydata["data"][0]["CorpSummary"] + "<br/>"
        content += "【经营范围】" + "<br/>"
        content += companydata["data"][0]["BusinessRange"] + "<br/>"

        content += "【股东研究】" + "<br/>"
        gdurl = "http://f10.eastmoney.com/ShareholderResearch/ShareholderResearchAjax?code=" + code2
        response = requests.get(gdurl)
        if response.text.find("DOCTYPE html") > 0:
            pass
        else:
            gddata = response.json()
            for gdinfo in gddata["sdltgd"][0]["sdltgd"]:
                content += gdinfo["gdmc"] + " -> " + gdinfo["gdxz"] + " -> " + gdinfo["zltgbcgbl"] + " -> " + gdinfo["bdbl"] + "<br/>"
        return content

    def getSinaCode(self,code):
        return code

    def getCodeInfo(self,code):
        calc = TushareCalc(code)
        return calc.getCodeInfo()

    def getHyInfo(self,sinacode):
        url = 'http://quote.eastmoney.com/' + sinacode + '.html'
        html = urllib.request.urlopen(url).read()
        html = html.decode('utf-8')  # python3版本中需要加入
        links = re.findall('<a.*?boardlist.html.*?<\/a>', html)

        dr = re.compile(r'<[^>]+>', re.S)
        hy = dr.sub('', links[0])

        links1 = re.findall('-.*?"', links[0])
        dm = links1[0][1:-1]

        hyinfo = {"hy":hy}
        hyinfo["dm"] = dm
        hyinfo["url"] = "http://quote.eastmoney.com/web/" + dm + ".html"
        return hyinfo

    def getChangeTitle(self,code):
        stockbaseinfo = StockBaseInfo()
        if code != "sh000001":
            txt = "概念板块： " + stockbaseinfo.getGaiNian(code) + "<br>--------------------------------------------<br>"
        else:
            txt = ""
        klineday = stockbaseinfo.getDfcfLineDay(code,30)
        zf = 0
        if "klines" in klineday:
            cdate = []
            close = []
            volum = []
            zf = []
            redcnt = 0
            redflag = False
            for row in klineday["klines"]:
                daydata = row.split(",")
                if float(daydata[2]) >= float(daydata[1]):
                    if redflag == False:
                        redflag = True
                        redcnt = 1
                    else:
                        redcnt += 1
                else:
                    redflag = False
                    redcnt = 0
                cdate.append(daydata[0])
                close.append(daydata[2])
                volum.append(daydata[5])
                zf.append(daydata[8]+"*")

            df = pd.DataFrame({'cdate': cdate,
                               'close': close,
                               'volum': volum,
                               'zf': zf})
            ma_list = [5, 10, 20]
            for ma in ma_list:
                df['close_ma_' + str(ma)] = df["close"].rolling(ma).mean()
            for ma in ma_list:
                df['volum_ma_' + str(ma)] = df["volum"].rolling(ma).mean()
            jslist = df.iloc[-1].tolist()
            txt += self.avglineByPrice(jslist[4],jslist[5])
            txt += self.isOnlineByPrice(jslist[4], jslist[1])
            txt += self.avglineByVolum(jslist[7], jslist[8])
            txt += self.isOnlineByVolum(jslist[7], jslist[2])
            if redcnt > 1:
                txt += "连续收阳天数为【" + str(redcnt) + "】天，"
            else:
                txt += "连续收阳天数为【" + str(redcnt) + "】天，"
            allzf = df["zf"].tail(5).sum()
            txt += self.calcZhangFu(allzf)
        return txt

    def avglineByPrice(self,price5,price10):
        txt = ''
        if float(price5) >= float(price10):
            txt += "5日线和10日线【金叉】，"
        else:
            txt += "5日线和10日线【死叉】，"
        return txt

    def isOnlineByPrice(self,price5,price):
        txt = ''
        if float(price) >= float(price5):
            txt += "股价在【5日线上】运行，"
        else:
            txt += "股价在【5日线下】运行，"
        return txt

    def avglineByVolum(self,price5,price10):
        txt = ''
        if float(price5) >= float(price10):
            txt += "成交量【金叉】，"
        else:
            txt += "成交量【死叉】，"
        return txt

    def isOnlineByVolum(self,price5,price):
        txt = ''
        if float(price) >= float(price5):
            txt += "成交量在【5日线上】运行，"
        else:
            txt += "成交量在【5日线下】运行，"
        return txt

    def calcZhangFu(self,zfstr):
        allzf = 0
        zflist = zfstr.split("*")
        for zf in zflist:
            if zf != "":
                allzf += float(zf)
        if allzf >= 5:
            return "5天涨幅总计【" + str(int(allzf)) + "%】，"
        else:
            return "5天涨幅总计【" + str(int(allzf)) + "%】，"